package com.yang.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yds
 * @program thread-study
 * @description 测试lock锁
 * @create 2020-09-23 17:01
 **/
public class TestLock {
    public static void main(String[] args) {
        ThreadLock t1=new ThreadLock();
        new Thread(t1,"小杨").start();
        new Thread(t1,"小张").start();

    }

}
class ThreadLock implements Runnable{
    public ReentrantLock lock=new ReentrantLock(); //使用jdk 5以后的显式锁 ReentrantLock
    public  int ticketNum=6;
    @Override
    public void run() {
        while(true){
            try{
                lock.lock();
                if(ticketNum>0){
                    System.out.println(Thread.currentThread().getName()+"：买到了第"+(7-ticketNum--)+"票");
                }else{
                    break;
                }
                Thread.sleep(100);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }
}